package com.demo.util;

import java.lang.annotation.Annotation;
import java.util.Map;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

@SuppressWarnings("all")
public class SpringContextUtil implements ServletContextListener {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	// Spring应用上下文环境
	private static ApplicationContext applicationContext;

	public static void setSpringContext(ApplicationContext applicationContext) {
		SpringContextUtil.applicationContext = applicationContext;
	}
	
	public static Object getBean(String beanName) {
		if(beanName.equals("redisTemplate")){
			System.out.println("");
		}
		if (!applicationContext.containsBean(beanName)) {
			if (!beanName.substring(0, 1).toLowerCase().equals(beanName.substring(0, 1)))
				beanName = beanName.substring(0, 1).toLowerCase() + beanName.substring(1);
			else if (!beanName.substring(0, 1).toUpperCase().equals(beanName.substring(0, 1))) {
				beanName = beanName.substring(0, 1).toUpperCase() + beanName.substring(1);
			}
		}
		return applicationContext.getBean(beanName);
	}

	public static <T> T getBean(String beanName, Class<T> clazz) {
		return (T) getBean(beanName);
	}

	public static <T> T getBean(Class<T> clazz) {
		String[] beans = applicationContext.getBeanNamesForType(clazz);
		if ((beans != null) && (beans.length > 0)) {
			return getBean(beans[0], clazz);
		}
		return null;
	}

	public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> clazz) {
		return applicationContext.getBeansWithAnnotation(clazz);
	}

	public void contextDestroyed(ServletContextEvent sce) {
		try {
			applicationContext = null;
			this.logger.info("spring配置卸载成功");
		} catch (Exception e) {
			this.logger.error("spring配置卸载失败", e);
		}
	}

	public void contextInitialized(ServletContextEvent sce) {
		try {
			applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext());
			this.logger.info("spring配置装载成功");
		} catch (Exception e) {
			this.logger.error("spring配置装载失败", e);
		}
	}
}
